package com.luck.easyfoodbatch.fragment;

import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v7.widget.DefaultItemAnimator;
import android.support.v7.widget.LinearLayoutManager;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.luck.easyfoodbatch.App;
import com.luck.easyfoodbatch.R;
import com.luck.easyfoodbatch.adapter.ShopCardAdapter;
import com.luck.easyfoodbatch.dialog.CustomDialog;
import com.luck.easyfoodbatch.entity.User;
import com.luck.easyfoodbatch.mvp.cart.CheckCartModel;
import com.luck.easyfoodbatch.mvp.cart.CheckCartPresenter;
import com.luck.easyfoodbatch.mvp.cart.CheckCartView;
import com.luck.easyfoodbatch.mvp.cart.DeleteCartModel;
import com.luck.easyfoodbatch.mvp.cart.DeleteCartPresenter;
import com.luck.easyfoodbatch.mvp.cart.DeleteCartView;
import com.luck.easyfoodbatch.mvp.cart.ModifyCartNumModel;
import com.luck.easyfoodbatch.mvp.cart.ModifyCartNumPresenter;
import com.luck.easyfoodbatch.mvp.cart.ModifyCartNumView;
import com.luck.easyfoodbatch.mvp.cart.PlaceOrderCartModel;
import com.luck.easyfoodbatch.mvp.cart.PlaceOrderCartPresenter;
import com.luck.easyfoodbatch.mvp.cart.PlaceOrderCartView;
import com.luck.easyfoodbatch.mvp.mine.CartListModel;
import com.luck.easyfoodbatch.mvp.mine.CartListPresenter;
import com.luck.easyfoodbatch.mvp.mine.CartListView;
import com.luck.easyfoodbatch.mvp.model.CartM;
import com.luck.easyfoodbatch.mvp.model.CheckCartM;
import com.luck.easyfoodbatch.mvp.model.Collect;
import com.luck.easyfoodbatch.mvp.model.ModifyNum;
import com.luck.easyfoodbatch.mvp.model.PlaceOrderM;
import com.luck.easyfoodbatch.mvp.order.ReturnDelOrderModel;
import com.luck.easyfoodbatch.mvp.order.ReturnDelOrderPresenter;
import com.luck.easyfoodbatch.mvp.order.ReturnDelOrderView;
import com.luck.easyfoodbatch.ui.ConfirmCartOrderActivity;
import com.luck.easyfoodbatch.ui.ShopHomeActivity;
import com.luck.easyfoodbatch.util.HttpUtil;
import com.luck.easyfoodbatch.util.SharedPreferencesUtil;
import com.luck.easyfoodbatch.util.T;
import com.luck.easyfoodbatch.util.Tools;
import com.luck.easyfoodbatch.util.Utils;
import com.luck.easyrecyclerview.EasyRecyclerView;
import com.luck.easyrecyclerview.adapter.RecyclerArrayAdapter;
import com.luck.easyrecyclerview.decoration.RecycleViewDivider;

import java.io.Serializable;
import java.text.DecimalFormat;
import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;

/**
 * author：luck
 * project：EasyFoodBatch
 * package：com.luck.easyfoodbatch.fragment
 * email：893855882@qq.com
 * data：16/9/22
 */
public class ShopCardFragment extends BaseFragment implements CartListView, ReturnDelOrderView, DeleteCartView, ModifyCartNumView, CheckCartView, PlaceOrderCartView, SwipeRefreshLayout.OnRefreshListener {

    @BindView(R.id.right_title)
    TextView rightTitle;
    @BindView(R.id.tv_delete)
    TextView tv_delete;
    @BindView(R.id.ll_bottom)
    LinearLayout ll_bottom;
    @BindView(R.id.recyclerView)
    EasyRecyclerView recyclerView;
    @BindView(R.id.ll_all)
    LinearLayout ll_all;
    @BindView(R.id.tv_settlement)
    TextView tv_settlement;
    @BindView(R.id.tv_all)
    TextView tv_all;
    @BindView(R.id.iv_cb)
    ImageView iv_cb;
    @BindView(R.id.rl_bottom)
    RelativeLayout rl_bottom;
    @BindView(R.id.tv_order_money)
    TextView tv_order_money;
    private View rootView;
    private ShopCardAdapter adapter;
    private List<CartM.DataBean.CartsBean> list = new ArrayList<>();
    private CartListModel listModel;  //购物车列表
    private DeleteCartModel cartModel;  //删除
    private ModifyCartNumModel cartNumModel; //改变数量
    private CheckCartModel checkCartModel;   //选中或撤选
    private int type = 0;//0撤选1选中
    private String address_id = "";
    private PlaceOrderCartModel placeOrderCartModel;  //通过购物车预下单
    private String money = "0";
    private ReturnDelOrderModel delOrderModel; //购物车预下单返回
    private boolean location = false;

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        if (rootView == null) {
            rootView = inflater.inflate(R.layout.fc_shop_card, container, false);
            ButterKnife.bind(this, rootView);
            View mStateBarFixer = rootView.findViewById(R.id.status_bar_fix);
            mStateBarFixer.setLayoutParams(new LinearLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT,
                    getStatusBarHeight(getActivity())));
            mStateBarFixer.setBackgroundColor(getResources().getColor(R.color.black));
            initView();
        }
        return rootView;
    }

    @Override
    public void onResume() {
        super.onResume();
        if (isCheckedLogin()) {
            User user = (User) App.getInstance().readObject(HttpUtil.USER_KEY);
            if (user != null) {
                User.DefaultAddressBean bean = user.getDefault_address();
                if (bean != null) {
                    address_id = bean.getAddress_id();
                }
            }
        }
    }

    /**
     * 初始化
     */
    private String p_id = "3";

    private void initView() {
        if (isCheckedLogin()) {
            p_id = (String) SharedPreferencesUtil.getData(getActivity(), HttpUtil.P_ID, "3");
            listModel = new CartListPresenter(this, mContext);
            listModel.requestCartList(p_id);
        }
        placeOrderCartModel = new PlaceOrderCartPresenter(this, mContext);
        LinearLayoutManager manager = new LinearLayoutManager(mContext);
        recyclerView.setItemAnimator(new DefaultItemAnimator());
        recyclerView.addItemDecoration(new RecycleViewDivider(
                mContext, LinearLayoutManager.HORIZONTAL, Utils.dip2px(mContext, 5), getResources().getColor(R.color.color_f2)));
        recyclerView.setLayoutManager(manager);
        adapter = new ShopCardAdapter(mContext, list, onRefresh, onCartNumber);
        recyclerView.setAdapterWithProgress(adapter);
        adapter.setOnItemClickListener(new RecyclerArrayAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(int position, View v) {
                Bundle bundle = new Bundle();
                Intent intent = new Intent();
                intent.setClass(mContext, ShopHomeActivity.class);
                bundle.putString("shop_id", list.get(position).getShop_id());
                intent.putExtras(bundle);
                mContext.startActivity(intent);
            }
        });
        adapter.addAll(list);
        recyclerView.setAdapter(adapter);
        recyclerView.setRefreshListener(this);
    }

    /**
     * 刷新商品数量和价格
     */
    public ShopCardAdapter.OnCartNumber onCartNumber = new ShopCardAdapter.OnCartNumber() {
        @Override
        public void onCartNumber(String cid, int num) {
            cartNumModel = new ModifyCartNumPresenter(ShopCardFragment.this, mContext);
            cartNumModel.requestModifyCart(cid, num, p_id);
        }
    };

    /**
     * 刷新购物车列表
     */
    public void onRefreshCart() {
        if (listModel == null) {
            listModel = new CartListPresenter(this, mContext);
        }
        listModel.requestCartList(p_id);
    }

    public ShopCardAdapter.OnRefresh onRefresh = new ShopCardAdapter.OnRefresh() {
        @Override
        public void onActivityRefresh(boolean isChecked, String cid, int position) {
            checkCartModel = new CheckCartPresenter(ShopCardFragment.this, mContext);
            StringBuffer sb = new StringBuffer();
            // 0撤选1选中
            if (isChecked) {
                type = 1;
            } else {
                type = 0;
            }
            CartM.DataBean.CartsBean cartsBean = list.get(position);
            List<CartM.DataBean.CartsBean.GoodsBean> goods = cartsBean.getGoods();
            for (CartM.DataBean.CartsBean.GoodsBean good : goods) {
                if (type == 0) {
                    // 0撤选
                    if (good.getIs_check() == 0) {
                        sb.append(good.getCid()).append(",");
                    }
                } else if (type == 1) {
                    // 1选中
                    if (good.getIs_check() == 1) {
                        sb.append(good.getCid()).append(",");
                    }
                }

            }
            cids = Tools.tempNames(sb.toString());
            showProgressDialog(getString(R.string.app_loading));
            checkCartModel.requestCheckCart(cids, type + "", p_id);
            Log.i("传的参数----->", cids + "\n" + type);
        }
    };

    @OnClick({R.id.right_title, R.id.tv_settlement, R.id.tv_delete, R.id.ll_all})
    public void onClick(View v) {
        String cids = "";
        String right = rightTitle.getText().toString().trim();
        switch (v.getId()) {
            case R.id.right_title:
                if (right.equals("编辑")) {
                    ll_bottom.setVisibility(View.GONE);
                    tv_delete.setVisibility(View.VISIBLE);
                    rightTitle.setText("完成");
                } else if (right.equals("完成")) {
                    rightTitle.setText("编辑");
                    ll_bottom.setVisibility(View.VISIBLE);
                    tv_delete.setVisibility(View.GONE);
                }
                break;
            case R.id.tv_settlement:
                // 结算
                cids = isCheckedShop();
                if (Tools.isNull(cids)) {
                    T.showToast(mContext, "请先选择需要结算的商品~");
                } else {
                    showProgressDialog(getString(R.string.app_loading));
                    if (location) {
                        placeOrderCartModel.requestPlaceOrderCart(cids, address_id);
                    } else {
                        placeOrderCartModel.requestPlaceOrderCart(cids, "");
                    }
                }
                break;
            case R.id.tv_delete:
                StringBuffer sb = new StringBuffer();
                for (CartM.DataBean.CartsBean item : list) {
                    List<CartM.DataBean.CartsBean.GoodsBean> goods = item.getGoods();
                    for (CartM.DataBean.CartsBean.GoodsBean good : goods) {
                        if (good.getIs_check() == 1) {
                            String cid = good.getCid();
                            sb.append(cid).append(",");
                        }
                    }
                }
                if (!Tools.isNull(sb.toString())) {
                    showDeleteDialog(sb.toString());
                } else {
                    T.showToast(mContext, "请先勾选要删除的购物车~");
                }
                break;
            case R.id.ll_all:
                // 全选
                String all = tv_all.getText().toString().trim();
                if (right.equals("完成")) {
                    // 如果是编辑状态下，就是全选删除，否则全选结算
                    ll_bottom.setVisibility(View.GONE);
                    tv_delete.setVisibility(View.VISIBLE);
                } else {
                    ll_bottom.setVisibility(View.VISIBLE);
                    tv_delete.setVisibility(View.GONE);
                }
                StringBuffer sbr = new StringBuffer();
                if (all.equals("全选")) {
                    iv_cb.setImageResource(R.mipmap.select_sel_1x);
                    tv_all.setText("完成");
                    type = 1;
                    for (CartM.DataBean.CartsBean item : list) {
                        item.setChecked(true);
                        List<CartM.DataBean.CartsBean.GoodsBean> goods = item.getGoods();
                        for (CartM.DataBean.CartsBean.GoodsBean good : goods) {
                            good.setIs_check(1);
                            sbr.append(good.getCid()).append(",");
                        }
                    }
                } else {
                    iv_cb.setImageResource(R.mipmap.select_def_1x);
                    tv_all.setText("全选");
                    type = 0;
                    for (CartM.DataBean.CartsBean item : list) {
                        item.setChecked(false);
                        List<CartM.DataBean.CartsBean.GoodsBean> goods = item.getGoods();
                        for (CartM.DataBean.CartsBean.GoodsBean good : goods) {
                            good.setIs_check(0);
                            sbr.append(good.getCid()).append(",");
                        }
                    }
                }
                adapter.onRefreshAdapter();// 子类也被选中，刷新
                adapter.notifyDataSetChanged();
                cids = Tools.tempNames(sbr.toString());
                if (checkCartModel == null) {
                    checkCartModel = new CheckCartPresenter(ShopCardFragment.this, mContext);
                }
                showProgressDialog(getString(R.string.app_loading));
                checkCartModel.requestCheckCart(cids, type + "", p_id);
                break;
        }
    }

    /**
     * 是否勾选过购物车内容
     *
     * @return
     */
    public String isCheckedShop() {
        StringBuffer sb = new StringBuffer();
        for (CartM.DataBean.CartsBean item : list) {
            List<CartM.DataBean.CartsBean.GoodsBean> goods = item.getGoods();
            for (CartM.DataBean.CartsBean.GoodsBean good : goods) {
                if (good.getIs_check() == 1) {
                    String cid = good.getCid();
                    sb.append(cid).append(",");
                }
            }
        }
        return Tools.tempNames(sb.toString());
    }

    /**
     * 删除购物车
     */
    private void showDeleteDialog(final String ids) {
        final CustomDialog dialog = new CustomDialog(mContext, App.screenWidth * 3 / 4,
                App.screenHeight / 4, R.layout.wind_base_dialog_xml, R.style.Theme_dialog);
        Button btn_cancel = (Button) dialog.findViewById(R.id.btn_cancel);
        Button btn_commit = (Button) dialog.findViewById(R.id.btn_commit);
        TextView tv_content = (TextView) dialog.findViewById(R.id.tv_content);
        tv_content.setText("确定要删除吗？");
        btn_cancel.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                dialog.dismiss();
            }
        });
        btn_commit.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                // 删除购物车
                String id = Tools.tempNames(ids);
                cartModel = new DeleteCartPresenter(ShopCardFragment.this, mContext);
                cartModel.requestDeleteCart(id, p_id);
                dialog.dismiss();
            }
        });
        dialog.show();
    }

    private String cids = "";

    @Override
    public void getCartListSuccess(CartM model) {
        if (model != null) {
            if (model.getStatus() == HttpUtil.RESULT_OK) {
                list = model.getData().getCarts();
                if (rl_bottom != null) {
                    if (list.size() == 0) {
                        rl_bottom.setVisibility(View.GONE);
                    } else {
                        rl_bottom.setVisibility(View.VISIBLE);
                    }
                }
                for (CartM.DataBean.CartsBean bean : list) {
                    int a = 0;
                    int b = 0;
                    List<CartM.DataBean.CartsBean.GoodsBean> goods = bean.getGoods();
                    for (CartM.DataBean.CartsBean.GoodsBean good : goods) {
                        if (good.getIs_check() == 1) {
                            a = 1;
                        } else {
                            b = 1;
                        }
                    }
                    if (a == 1 && b == 0) {
                        // 当前分类下全选中了
                        bean.setChecked(true);
                    }
                }

                int c = 0;
                int d = 0;
                for (CartM.DataBean.CartsBean bean : list) {
                    if (bean.isChecked()) {
                        c = 1;
                    } else {
                        d = 1;
                    }
                }

                if (c == 1 && d == 0) {
                    // 全选
                    tv_all.setText("取消");
                    iv_cb.setImageResource(R.mipmap.select_sel_1x);
                } else if (c == 0 && d == 1) {
                    // 没一个选中
                    tv_all.setText("全选");
                    iv_cb.setImageResource(R.mipmap.select_def_1x);
                } else if (c == 1 && d == 1) {
                    // 部分选中
                    tv_all.setText("全选");
                    iv_cb.setImageResource(R.mipmap.select_def_1x);
                }
                money = model.getData().getTotal_price() + "";
                DecimalFormat df = new DecimalFormat("0.00");
                Double ds = Double.valueOf(money.trim());
                df.format(ds);
                tv_order_money.setText("￥" + df.format(ds));
                adapter.clear();
                adapter.addAll(list);
                adapter.setList(list);
                adapter.notifyDataSetChanged();
            } else {
                T.showToast(mContext, model.getMsg());
            }
        }
    }

    @Override
    public void deleteCartSuccess(CartM model) {
        if (model != null) {
            if (model.getStatus() == HttpUtil.RESULT_OK) {
                showProgressDialog(getString(R.string.app_loading));
                listModel.requestCartList(p_id);
                rightTitle.setText("编辑");
                ll_bottom.setVisibility(View.VISIBLE);
                tv_delete.setVisibility(View.GONE);
                tv_all.setText("全选");
                iv_cb.setImageResource(R.mipmap.select_def_1x);
            } else {
                T.showToast(mContext, model.getMsg());
            }
        }
    }

    @Override
    public void modifyCartNumSuccess(ModifyNum model) {
        if (model != null) {
            if (model.getStatus() == HttpUtil.RESULT_OK) {
                listModel.requestCartList(p_id);
            } else {
                T.showToast(mContext, model.getMsg());
            }
        }
    }

    @Override
    public void checkCartSuccess(CheckCartM model) {
        if (model != null) {
            if (model.getStatus() == HttpUtil.RESULT_OK) {
                listModel.requestCartList(p_id);
            } else {
                T.showToast(mContext, model.getMsg());
            }
        }
    }


    @Override
    public void placeOrderCartSuccess(PlaceOrderM model) {
        if (model != null) {
            if (model.getStatus() == HttpUtil.RESULT_OK) {
                cids = isCheckedShop();
                List<PlaceOrderM.DataBean> list = model.getData();
                Intent intent = new Intent();
                Bundle bundle = new Bundle();
                bundle.putSerializable("list", (Serializable) list);
                bundle.putString("cids", cids);
                bundle.putString("money", money);
                intent.setClass(mContext, ConfirmCartOrderActivity.class);
                intent.putExtras(bundle);
                startActivityForResult(intent, 200);
            } else {
                T.showToast(mContext, model.getMsg());
            }
        }
    }

    @Override
    public void httpStatusError() {
        showToast("网络错误,请检查网络");

    }

    @Override
    public void hideLoading() {
        hideShowProgress();
    }


    @Override
    public void onRefresh() {
        listModel = new CartListPresenter(this, mContext);
        listModel.requestCartList(p_id);
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == getActivity().RESULT_OK) {
            switch (requestCode) {
                case 200:
                    if (data != null) {
                        String order_ids = data.getStringExtra("order_ids");
                        delOrderModel = new ReturnDelOrderPresenter(ShopCardFragment.this, mContext);
                        delOrderModel.requestReturnDelOrder(order_ids);
                    }
                    break;
            }
        }
    }

    @Override
    public void returnDelOrderSuccess(Collect model) {
        if (model != null) {
            if (model.getStatus() == HttpUtil.RESULT_OK) {
                Log.i("成功", model.getMsg());
            }
        }
    }

//    @Override
//    public void myAddressSuccess(MyAddress model) {
//        if (model != null) {
//            if (model.getStatus() == HttpUtil.RESULT_OK) {
//               List<MyAddress.DataBean> list = model.getData();
//                if (list != null && list.size() > 0) {
//                    for (MyAddress.DataBean bean : list) {
//                        // 取默认地址
//                        if (bean.getIs_default() == 1) {
//                            if (bean.getProvince().equals(p_id)) {
//                                location=true;
//                            }
//                                break;
//                            }
//                        }
//                    }
//                }
//            }
//    }
}
